package com.sdx.payment.system.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.payment.system.entity.*;
import com.sdx.payment.system.service.*;
import com.sdx.payment.system.web.query.*;

/**
 * 支付账号 接口
 */
@RequestMapping("/system/cfgThirdRecord")
@Controller
public class CfgThirdRecordController{
	private static final Logger log = LoggerFactory.getLogger(CfgThirdRecordController.class);
    private static final String MODEL = "/system/cfgThirdRecord";


    @Autowired
    private CfgThirdRecordService cfgThirdRecordService;
    
    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping("/index.do")
    @Function("system.cfgThirdRecord.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        return view;
    }

    @GetMapping("/edit.do")
    @Function("system.cfgThirdRecord.edit")
    @ResponseBody
    public ModelAndView edit(String platformType, String unid) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
	    CfgThirdRecord id = new CfgThirdRecord();
	    id.setPlatformType(platformType);
	    id.setUnid(unid);
        CfgThirdRecord cfgThirdRecord = cfgThirdRecordService.queryById(id);
        view.addObject("cfgThirdRecord", cfgThirdRecord);
		try {
			view.addObject("cfgThirdRecordJson", JacksonUtils.toJsonString(cfgThirdRecord,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("system.cfgThirdRecord.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("system.cfgThirdRecord.query")
    @ResponseBody
    public JsonResult<PageQuery> list(CfgThirdRecordQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        cfgThirdRecordService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,CfgThirdRecord cfgThirdRecord
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";


    	if (isNew) {
			cfgThirdRecordService.save(cfgThirdRecord);
		} else {
			cfgThirdRecordService.updateTemplate(cfgThirdRecord);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("system.cfgThirdRecord.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)CfgThirdRecord cfgThirdRecord
		)
    {

        return save(true,cfgThirdRecord
		);
    }

    @PostMapping("/update.json")
    @Function("system.cfgThirdRecord.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  CfgThirdRecord cfgThirdRecord
		) {
		return save(false,cfgThirdRecord
		);
    }


   
    @GetMapping("/view.json")
    @Function("system.cfgThirdRecord.query")
    @ResponseBody
    public JsonResult<CfgThirdRecord>queryInfo(String unid) {
        CfgThirdRecord cfgThirdRecord = cfgThirdRecordService.queryById( unid);
        return  JsonResult.success(cfgThirdRecord);
    }

    @PostMapping("/delete.json")
    @Function("system.cfgThirdRecord..del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        cfgThirdRecordService.batchDelCfgThirdRecord(idList);
        return JsonResult.success();
    }
    
    
    @PostMapping("/excel/export.json")
    @Function("system.cfgThirdRecord.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,CfgThirdRecordQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此cfgThirdRecordService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/system/cfgThirdRecord/你的excel模板文件名字.xls";
        PageQuery<CfgThirdRecord> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<CfgThirdRecord> list =cfgThirdRecordService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("支付账号_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping("/excel/import.do")
    @Function("system.cfgThirdRecord.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }
    
    

}
